﻿using BarcodeDelay.HttpClient;
using BarcodeDelay.utility;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BarcodeDelay.view
{
    public partial class FrmRigister : Form
    {
        public event Action DoneRegInfo;
        public FrmRigister()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnTry_Click(object sender, EventArgs e)
        {
            try
            {
                string strSiteName = this.tbSiteName.Text;
                if(strSiteName.Length<1)
                {
                    MessageBox.Show("试用站点信息不能为空");
                    return;
                }
                if (MessageBox.Show("确定当前使网点名称："+ strSiteName+" 与梧桐系统里完全一致？", "网点名称确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                {
                    return;
                }
                if (tbSiteName.Text.Trim().Length > 1)
                {
                    writeTbFile(tbSiteName.Text.Trim());
                }

                this.btnTry.Enabled = false;
                
                string postDataTime = "{\"action\":\"tryApply\",\"siteName\":\"" + strSiteName + "\",\"timestamp\":\"" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"token\":\"" + null + "\"}";
                string ctime = HttpUtility.getServerTime(postDataTime);
                if (ctime == "")
                {
                    ctime = System.DateTime.Now.ToString();
                }
                DateTime dtd = Convert.ToDateTime(ctime);            

                string strToken = Utility.GenerateMD5(dtd.ToString("yyyy-MM-dd HH:mm:ss"));
                string postData = "{\"action\":\"tryApply\",\"siteName\":\""+ strSiteName + "\",\"timestamp\":\""+ dtd.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"token\":\""+strToken+"\"}";
                if (HttpUtility.getMyInfo(postData))
                {
                    MessageBox.Show("试用申请成功");
                }
                else
                {
                    MessageBox.Show("试用申请失败，请联系客服");
                }
                DoneRegInfo.Invoke();




            }
            catch(Exception ex)
            {

            }
        }


        private void writeTbFile(string strSiteName)
        {
            try
            {
                string delFile = System.Environment.CurrentDirectory + "\\" + StoParams.Instance.siteTxtPath;
                if(delFile.EndsWith("txt"))
                {
                    File.Delete(delFile);
                    FileStream bFile = new FileStream(delFile, FileMode.Create);
                    StreamWriter swb = null;
                    if (swb == null)
                    {
                        swb = new StreamWriter(bFile);
                    }
                    StoParams.Instance.register_site = strSiteName;
                    swb.WriteLine("regsite " + strSiteName);

                    swb.Close();
                }
                

            }
            catch (Exception ex)
            {

            }
        }

        private void FrmRigister_Load(object sender, EventArgs e)
        {
            try
            {
                if(StoParams.Instance.user_status==2|| StoParams.Instance.register_site==null)
                {
                    btnTry.Enabled = true;
                }
                else
                {
                    btnTry.Enabled = false;
                }
                this.tbSiteName.Text = StoParams.Instance.register_site;
                this.tbRegCode.Text = StoParams.Instance.regCode;
                if (StoParams.Instance.regCode.Length>1)
                {
                    this.btnRegister.Enabled = false;
                    this.btnTry.Enabled = false;                   
                }
                if(StoParams.Instance.day_left<5)
                {
                    this.btnRegister.Enabled = true;
                }
                if(StoParams.Instance.register_site!=null&&StoParams.Instance.register_site!="")
                {
                    this.tbInfo.Text = "每日额度" + StoParams.Instance.day_total + " 会员有效期至" + StoParams.Instance.endDate;
                }
            }
            catch(Exception ex)
            {

            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            string strSiteName = this.tbSiteName.Text;
            if (strSiteName.Length < 1)
            {
                MessageBox.Show("站点信息不能为空");
                return;
            }
            if (MessageBox.Show("确定当前使网点名称：" + strSiteName + " 与梧桐系统里完全一致？", "网点名称确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return;
            }
            string strRegCode = this.tbRegCode.Text;
            if(strRegCode.Length<10)
            {
                MessageBox.Show("注册码不能为空");
                return;
            }
            DateTime dtd = System.DateTime.Now;
            string strToken = Utility.GenerateMD5(dtd.ToString("yyyy-MM-dd HH:mm:ss"));
            string postData = "{\"action\":\"regApply\",\"siteName\":\"" + strSiteName + "\",\"timestamp\":\"" + dtd.ToString("yyyy-MM-dd HH:mm:ss") + "\",\"token\":\"" + strToken + "\"" + ",\"regCode\":\"" + strRegCode + "\"}";
            
            JObject jsonObj=HttpUtility.regInfo(postData);
            if(jsonObj!=null)
            {
                JToken msg = (JToken)jsonObj["msg"];
                if (msg.ToString().Contains("regcode in use"))
                {
                    MessageBox.Show("此注册码已使用");
                    return;
                }
                if (msg.ToString().Contains("invalid regcode"))
                {
                    MessageBox.Show("此注册码无效");
                    return;
                }
                
                JToken dayQueryCount = (JToken)jsonObj["queryLimit"];
                JToken QueryUrl = (JToken)jsonObj["queryUrl"];
                JToken dayLeftCount = (JToken)jsonObj["todayLeft"];
                JToken regCode = (JToken)jsonObj["regCode"];
                JToken status = (JToken)jsonObj["status"];

                int istatus = Convert.ToInt32(status.ToString());

                int idayQueryCount = Convert.ToInt32(dayQueryCount.ToString());
                StoParams.Instance.day_total = idayQueryCount;
                StoParams.Instance.queryUrl = QueryUrl.ToString();
                StoParams.Instance.day_left = Convert.ToInt32(dayLeftCount);
                StoParams.Instance.regCode = regCode.ToString();
                StoParams.Instance.register_site = tbSiteName.Text.Trim();
                StoParams.Instance.user_status = istatus;
                MessageBox.Show("注册成功");
                if (tbSiteName.Text.Trim().Length > 1)
                {
                    writeTbFile(tbSiteName.Text.Trim());
                    DoneRegInfo.Invoke();
                }

            }
            else
            {
                MessageBox.Show("无法连接远程服务器，请联系客服 电话：17721319031");
            }



            

        }
    }
}
